// JETNUKE

/*
 * Copyright (c) 2004-2006 by Andrea Mazzolini
 * [andreamazzolini@users.sourceforge.net] http://www.jetnuke.org
 * 
 * 
 * This program is free software; you can redistribute it and/or modify it under
 * the terms of the GNU General Public License as published by the Free Software
 * Foundation; either version 2 of the License, or (at your option) any later
 * version.
 * 
 * This program is distributed in the hope that it will be useful, but WITHOUT
 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
 * FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
 * details.
 * 
 * You should have received a copy of the GNU General Public License along with
 * this program; if not, write to the Free Software Foundation, Inc., 59 Temple
 * Place - Suite 330, Boston, MA 02111-1307, USA.
 *  
 */
package org.jetnuke.servlets.utilities;

import java.util.ArrayList;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Set;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.jetnuke.dao.DataAccessDriver;
import org.jetnuke.entities.Censore;
import org.jetnuke.entities.MainConfig;

public class StringUtils {
	public static String check_words(int censorMode, String censorReplace,
			String inputText, List censorList) {
		if (inputText == null)
			return inputText;
		if (censorMode != 0) {

			int count = censorList.size();
			if (/* is_array($CensorList) */true) {

				if (censorMode == 1) {
					for (int i = 0; i < count; i++) {//Exact Match
						Pattern pt = Pattern.compile(((String) censorList
								.get(i))
								+ "([^a-zA-Z0-9])", Pattern.CASE_INSENSITIVE
								| Pattern.UNICODE_CASE);
						Matcher mt = pt.matcher(inputText);
						mt.replaceAll(censorReplace);
						//inputText=inputText.replaceAll(,censorReplace);
						//$EditedMessage =
						// eregi_replace("$CensorList[$i]([^a-zA-Z0-9])","$Replace\\1",$EditedMessage);
					}
				} else if (censorMode == 2) {
					for (int i = 0; i < count; i++) {//Word at the beginning

						Pattern pt = Pattern
								.compile("(^|[^[:alnum:]])"
										+ ((String) censorList.get(i)),
										Pattern.CASE_INSENSITIVE
												| Pattern.UNICODE_CASE);
						Matcher mt = pt.matcher(inputText);
						inputText = mt.replaceAll(censorReplace);

						//inputText=inputText.replaceAll("(^|[^[:alnum:]])"+((String)censorList.get(i)),censorReplace);
						//$EditedMessage =
						// eregi_replace("(^|[^[:alnum:]])$CensorList[$i]","\\1$Replace",$EditedMessage);
					}
				} else if (censorMode == 3) {//Anywhere in the text
					for (int i = 0; i < count; i++) {
						//inputText=inputText.replaceAll(((String)censorList.get(i)),censorReplace);

						Pattern pt = Pattern.compile(((String) censorList
								.get(i)), Pattern.CASE_INSENSITIVE
								| Pattern.UNICODE_CASE);
						Matcher mt = pt.matcher(inputText);
						inputText = mt.replaceAll(censorReplace);

						//$EditedMessage =
						// eregi_replace("$CensorList[$i]","$Replace",$EditedMessage);
					}
				}
			}
		}
		return inputText;
	}

	public static String filterText(int censoreMode, String censorReplace,
			String inputText, List censorList, boolean noHTML) {
		String tmp = check_words(censoreMode, censorReplace, inputText,
				censorList);
		if(noHTML){
			tmp=removeHtml(tmp);
		}else{
			tmp=filterHtml(tmp,false);
		}
		//tmp = check_html(tmp, false);
		return tmp;
	}

	private static Pattern ampPt = Pattern.compile("&");

	private static Pattern quotPt = Pattern.compile("\"");

	private static Pattern ltPt = Pattern.compile("<");

	private static Pattern gtPt = Pattern.compile(">");

	public static String htmlspecialchars(String inputText) {
		String tmp = ampPt.matcher(inputText).replaceAll("&amp;");
		tmp = quotPt.matcher(tmp).replaceAll("&quot;");
		tmp = ltPt.matcher(tmp).replaceAll("&lt;");
		tmp = gtPt.matcher(tmp).replaceAll("&gt;");
		return tmp;
	}

	public static String filterText(String inputText, boolean noHTML){
		return filterText(inputText,noHTML,false);
	}
	public static String filterText(String inputText, boolean noHTML, boolean allowImages) {
		List censorList = new ArrayList();
		Iterator it;
		int censorMode = 3;
		String censorReplace = "";
		try {
			it =DataAccessDriver.getInst().newCensoreDAO().selectAll().iterator();// censorePeer.doSelect(new Criteria()).iterator();
			while (it.hasNext()) {
				censorList.add(((Censore) it.next()).getWORD());
			}
			MainConfig config = DataAccessDriver.getInst().newMainConfigDAO().getMainConfig();//(MainConfig) main_configPeer.doSelect(
					//new Criteria()).get(0);
			censorMode = config.getCENSORMODE();
			censorReplace = config.getCENSORREPLACE();
		} catch (Exception e) {
		}

		//.getAttribute("MAIN_CONFIG");

		String tmp = check_words(censorMode, censorReplace, inputText,
				censorList);
		if(noHTML){
			tmp=removeHtml(tmp);
		}else{
			tmp=filterHtml(tmp,allowImages);
		}
		return tmp;
	}

	public static String filterText(int censoreMode, String censorReplace,
			String inputText, boolean noHTML) {
		List censorList = new ArrayList();
		Iterator it;
		try {
			it = DataAccessDriver.getInst().newCensoreDAO().selectAll().iterator();
			while (it.hasNext()) {
				censorList.add(((Censore) it.next()).getWORD());
			}
		} catch (Exception e) {
		}
		return filterText(censoreMode, censorReplace, inputText, censorList,
				noHTML);
	}

	private static Pattern img_pt = Pattern.compile(
			"<[\\p{Space}]*img[\\p{Space}]*([^>]*)[\\p{Space}]*>", // Delete all
																   // img tags
			Pattern.CASE_INSENSITIVE);

	private static Pattern blank_pt = Pattern
			.compile("<[\\p{Space}]*([^>]*)[\\p{Space}]*>");

	private static Pattern blank_pt2 = Pattern
			.compile("<[\\p{Space}]*/\\p{Space}]*([^>]*)[\\p{Space}]*>");

	private static Pattern a_pt = Pattern
			.compile("<a[^>]*href[\\p{Space}]*=[\\p{Space}]*\"?[\\p{Space}]*([^\" >]*)[\\p{Space}]*\"?[^>]*>");

	private static Pattern script_pt = Pattern
			.compile("<a[^>]*href[\\p{Space}]*=[\\p{Space}]*\"?javascript[\\p{Punct}]*\"?[^>]*>");

	private static Pattern tag_pt = Pattern
			.compile("<(/?[\\p{Alpha}]*[\\p{Digit}]*)[\\p{Space}]*([^>]*)>");

	private static Pattern unescape_quote = Pattern.compile("\\\\'");

	private static Pattern double_back = Pattern.compile("\\\\\\\\");

	private static String stripslashes(String inputString) {
		String tmp = unescape_quote.matcher(inputString).replaceAll("'");
		return double_back.matcher(tmp).replaceAll("\\\\");
	}

	public static void main(String args[]){
	//	String test="<h1><a name=\"_Toc99970974\">1&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; Introduction to JetNuke</a></h1><div>&nbsp;</div><h3><a name=\"_Toc99970975\">1.1.&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; What is JetNuke?</a></h3><div>&nbsp;</div><div>JetNuke is free software, released under the GNU License.</div><div>&nbsp;</div>";
		//System.out.println(filterHtml(test,false));
		String test2="<a href=\"http://www.jetnuke.org\">jetnuke</a><img src=\"http://www.google.com/intl/en/images/logo.gif\">";
		System.out.println(filterHtml(test2,true));
	}
	
	private static String privateFilterHtmlAllowImages(String inputString){
		inputString = stripslashes(inputString);
		Matcher mt2 = blank_pt.matcher(inputString);
		inputString = mt2.replaceAll("<$1>");

		Matcher mt21 = blank_pt2.matcher(inputString);
		inputString = mt21.replaceAll("</$1>");

		Matcher mt5 = a_pt.matcher(inputString);
		inputString = mt5.replaceAll("<a href=\"$1\">");

		Matcher mt3 = script_pt.matcher(inputString);
		inputString = mt3.replaceAll("");
		return inputString;
	}
	
	private static String privateFilterHtmlNoImages(String inputString){
		inputString=privateFilterHtmlAllowImages(inputString);
		Matcher mt = img_pt.matcher(inputString);
		inputString = mt.replaceAll("");
		return inputString;
	}
	
	private static Set getAllowableHtml(){
		HashSet allowableHTML = new HashSet();
		allowableHTML.add("b");
		allowableHTML.add("i");
		allowableHTML.add("u");
		allowableHTML.add("sub");
		allowableHTML.add("sup");
		allowableHTML.add("strike");
		allowableHTML.add("a");
		allowableHTML.add("em");
		allowableHTML.add("br");
		allowableHTML.add("strong");
		allowableHTML.add("blockquote");
		allowableHTML.add("tt");
		allowableHTML.add("li");
		allowableHTML.add("ol");
		allowableHTML.add("ul");
		allowableHTML.add("span");
		allowableHTML.add("font");
		allowableHTML.add("h1");
		allowableHTML.add("h2");
		allowableHTML.add("h3");
		allowableHTML.add("p");
		return allowableHTML;
	}
	
	public static String removeHtml(String inputString){
		
		String tmp = "";
		while (true) {
			Matcher mt0 = tag_pt.matcher(inputString);
			if (!mt0.find()) {
				tmp = tmp + inputString;
				break;
			}

			String reg0 = mt0.group();
			String reg1 = mt0.group(1);
			//if (mt0.groupCount() > 1)
			//	reg2 = mt0.group(2);
			int i = inputString.indexOf(reg0);
			int l = reg0.length();
			String tag = null;
			if (reg1.length()>0 && reg1.charAt(0) == '/') {
				tag = reg1.substring(1).toLowerCase().trim();
			} else {
				tag = reg1.toLowerCase().trim();
			}
			tag = "";
			
			tmp = tmp + inputString.substring(0, i) + tag;
			inputString = inputString.substring(i + l);
		}
		return tmp;
	}
	
	private static String filterHtml(String inputString, boolean allowImages) {

		Set allowableHTML = getAllowableHtml();
		if(allowImages){
			inputString=privateFilterHtmlAllowImages(inputString);
			allowableHTML.add("img");
		}else{
			inputString=privateFilterHtmlNoImages(inputString);
		}

		String tmp = "";
		while (true) {
			Matcher mt0 = tag_pt.matcher(inputString);
			if (!mt0.find()) {
				tmp = tmp + inputString;
				break;
			}

			String reg0 = mt0.group();
			String reg1 = mt0.group(1);
			String reg2 = "";
			if (mt0.groupCount() > 1)
				reg2 = mt0.group(2);
			int i = inputString.indexOf(reg0);
			int l = reg0.length();
			String tag = null;
			if (reg1.length()>0 && reg1.charAt(0) == '/') {
				tag = reg1.substring(1).toLowerCase().trim();
			} else {
				tag = reg1.toLowerCase().trim();
			}
			if ( allowableHTML.contains(tag)) {
				if ( reg1.length()>0 && reg1.charAt(0) == '/') {
					tag = "</" + tag + ">";
				} else if (reg2.equals("") || !(reg1.equals("a") || reg1.equals("img") || reg1.equals("font") || reg1.equals("span") || reg1.equals("h1") || reg1.equals("h2") || reg1.equals("h3") ||  reg1.equals("p"))) {
					tag = "<" + tag + ">";
				} else {
					//TODO reg2=delQuotes(reg2);
					//reg2 = reg2.replaceAll("&", "&amp;");
					tag = "<" + tag + " " + reg2 + ">";
				}
			} else {
				tag = "";
			}
			tmp = tmp + inputString.substring(0, i) + tag;
			inputString = inputString.substring(i + l);
		}
		return tmp;
	}
	public static String findMimeType(String string) {
		String filename=string.toLowerCase();
		String ret="?";
		if(filename.endsWith(".xls")){
			ret="application/vnd.ms-excel";
		}else if (filename.endsWith(".pdf")){
			ret="application/pdf";
		}else if (filename.endsWith(".doc")){
			ret="application/msword";
		}else if (filename.endsWith(".png")){
			ret="image/png";
		}else if (filename.endsWith(".txt")){
			ret="text/plain";
		}else if (filename.endsWith(".gif")){
			ret="image/gif";
		}else if (filename.endsWith(".jpg")||filename.endsWith(".jpeg")){
			ret="image/jpeg";
		}else if (filename.endsWith(".bmp")){
			ret="image/bmp";
		}else if (filename.endsWith(".zip")){
			ret="application/zip";
		}else if (filename.endsWith(".ppt")){
			ret="application/powerpoint";
		}else if (filename.endsWith(".xlm")){
			ret="application/xml";
		}else if (filename.endsWith(".html")||filename.endsWith(".htm")){
			ret="text/html";
		}
		return ret;
	}
	static final Pattern ptSimpleFileName=Pattern.compile("[^a-z0-9_.]",Pattern.CASE_INSENSITIVE);
	public static String getSimpleFileName(String name){
		String separator = "/";
		int index = name.indexOf(separator);
		
		if (index == -1) {
			separator = "\\";
			index = name.indexOf(separator);
		}
		
		if (index > -1) {
			if (separator.equals("\\")) {
				separator = "\\\\";
			}
			
			String[] p = name.split(separator);
			name = p[p.length - 1];
		}
		//String dir=SystemGlobals.getValue(ConfigKeys.ATTACHMENTS_STORE_DIR) + "/blog/"+ui.getID()+"/";
		//new File(dir).mkdirs();
		String simplifiedName=ptSimpleFileName.matcher(name).replaceAll("");
		return simplifiedName;
	}
}